package com.hengxinguotong.zhihuichengjian.database;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.hengxinguotong.zhihuichengjian.bean.News;
import com.hengxinguotong.zhihuichengjian.bean.NewsInfo;

import java.util.ArrayList;


/**
 * Created by Administrator on 2017/8/31.
 */

public class NewsDAO
{
    private SQLiteDatabase sqLiteDatabase;

    public NewsDAO(Context context)
    {
        sqLiteDatabase = MyDatabaseHelper.getInstance(context);
    }

    public void addNews(News news)
    {
        String addNews_sql = "insert into news(id,title,content,link,path) values(?,?,?,?,?);";
        Object[] add_bindArgs = {news.getId(), news.getTitle(), news.getContent(), news.getLink(), news.getPath()};
        sqLiteDatabase.execSQL(addNews_sql, add_bindArgs);
    }

    public void delNews(News news)
    {
        String delNews_sql = "delete from news where id=?;";
        Object[] del_bindArgs = {news.getId()};
        sqLiteDatabase.execSQL(delNews_sql, del_bindArgs);
    }

    public void updateNews(News news)
    {
        String updateNews_sql = "update news set title=?,content=?,link=?,path=? where id=?;";
        Object[] update_bindArgs = {news.getTitle(), news.getContent(), news.getLink(), news.getPath(), news.getId()};
        sqLiteDatabase.execSQL(updateNews_sql, update_bindArgs);
    }

    public ArrayList<News> selectAll()
    {
        ArrayList<News> list = new ArrayList<News>();
        String selectAll_sql = "select * from news;";
        Cursor cursor = sqLiteDatabase.rawQuery(selectAll_sql, null);
        while (cursor.moveToNext())
        {
            News news = new News();
            news.setId(cursor.getString(cursor.getColumnIndex("id")));
            news.setTitle(cursor.getString(cursor.getColumnIndex("title")));
            news.setContent(cursor.getString(cursor.getColumnIndex("content")));
            news.setLink(cursor.getString(cursor.getColumnIndex("link")));
            news.setPath(cursor.getString(cursor.getColumnIndex("path")));
            list.add(news);
        }
        return list;
    }

    public News selectNewsById(int id)
    {
        News news = new News();
        String selectNews_sql = "select * from news where id=?;";
        String[] selectNews_bindArgs = {id + ""};
        Cursor cursor = sqLiteDatabase.rawQuery(selectNews_sql, selectNews_bindArgs);
        while (cursor.moveToNext())
        {
            news.setId(cursor.getString(cursor.getColumnIndex("id")));
            news.setTitle(cursor.getString(cursor.getColumnIndex("title")));
            news.setContent(cursor.getString(cursor.getColumnIndex("content")));
            news.setLink(cursor.getString(cursor.getColumnIndex("link")));
            news.setPath(cursor.getString(cursor.getColumnIndex("path")));
        }
        return news;
    }

}
